'Copyright (c) Vanatec.  All rights reserved.
'
' usage example:
'
' ' Get ObjectScope from Helper
' Dim scope As IObjectScope = ObjectScopeProvider1.ObjectScope
' ' start transaction
' scope.Transaction.Begin()
' ' create new persistent object person and add to scope
' Dim p As New Person
' scope.Add(p)
' ' commit transction
' scope.Transaction.Commit()
'
Imports OpenAccess
Imports OpenAccess.Util

Public Class ObjectScopeProvider1
	Implements IObjectScopeProvider
	Private _myDatabase As Database
	Private _myScope As IObjectScope

	Private Shared theObjectScopeProvider1 As ObjectScopeProvider1

	Public Sub New ()
    End Sub

	' Allows a dynamically loaded assembly to open the database.
	' Must be called before the ObjectScope is aquired.
    Public Shared Sub AdjustForDynamicLoad()
        If theObjectScopeProvider1 Is Nothing Then
            theObjectScopeProvider1 = New ObjectScopeProvider1()
        End If

        If theObjectScopeProvider1._myDatabase Is Nothing Then
            Dim assumedInitialConfiguration As String
            assumedInitialConfiguration = "<openaccess>" _
                           & "<references>" _
                           & "<reference assemblyname='PLACEHOLDER' configrequired='True'/>" _
                           & "</references>" _
                           & "</openaccess>"
            Dim repl As String = "PLACEHOLDER"
            Dim dll As System.Reflection.Assembly = theObjectScopeProvider1.GetType().Assembly
            assumedInitialConfiguration = assumedInitialConfiguration.Replace(repl, dll.GetName().Name)
            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc.LoadXml(assumedInitialConfiguration)
            Dim allDlls(1) As System.Reflection.Assembly
            allDlls(0) = dll

            theObjectScopeProvider1._myDatabase = OpenAccess.Database.Get("DatabaseConnection", _
											xmlDoc.DocumentElement, allDlls)
        End If
    End Sub

    Public Shared Function Database() As Database
		If theObjectScopeProvider1 Is Nothing Then
			theObjectScopeProvider1 = New ObjectScopeProvider1()
        End If

		If theObjectScopeProvider1._myDatabase Is Nothing Then
			theObjectScopeProvider1._myDatabase = OpenAccess.Database.Get( "DatabaseConnection" )
        End If

		Return theObjectScopeProvider1._myDatabase
    End Function

    Public Shared Function ObjectScope() As IObjectScope
        Database()

		If theObjectScopeProvider1._myScope Is Nothing Then
            theObjectScopeProvider1._myScope = GetNewObjectScope()
        End If

		Return theObjectScopeProvider1._myScope
    End Function

    Public Shared Function GetNewObjectScope() As IObjectScope
        Dim db As Database = Database()

		Dim newScope As IObjectScope = db.GetObjectScope()
        Return newScope
    End Function
End Class
